<?php


namespace app\self\controller;


use think\Controller;
use think\Db;

class Upload    extends Controller
{
    public function index()
    {
        return view();
    }

    //列表 上传文件
    public function data_list(){
        $map = [];
        $arr=input("rel");
        if($arr){
            $map['rel'] =$arr;
            $list = Db::name('ps_upload')->where($map)->select();
            return json($list);
        }else{
            return '';
        }
    }

    /**
     * by   hugh
     * use  上传文件
     * time 2020/5/13 16:38
     */
    public function upfile()
    {

        $rel = input('rel');
        $size_limit = input('size');

        //验证
        if(!isset($_FILES["file"])) {
            return json(array('code' => 1,'text'=>"No File"));
        }



        if($_FILES["file"]['error'] > 0){
            return json(array('code' => 1,'text'=>"Error：" . $_FILES["file"]['error']));
        }


        //文件信息
        $file_path = $_FILES["file"]["tmp_name"];
        $file_size = $_FILES["file"]["size"];
        $file_type = $_FILES["file"]["type"];
        $file_name = $_FILES["file"]["name"];
        $arr = pathinfo($file_name);
        $file_name_out = $arr['filename'];
        if(isset($arr['extension'])){
            $ext = $arr['extension'];
        } else {
            $ext = "";
        }

        //短期对策不能超过5M,长期对策不能超过20M
        $up_info = Db::name('ps_upload')->where('rel',$rel)->select();
        $size = 0;
        foreach ($up_info as $k => $v) {
            $size += $v['file_size'];
        }


        //创建文件夹
        $root = ROOT_PATH . "public";
        $path = "/upload/".date("Y/m/d/");
        if (!file_exists($root.$path)){
            mkdir ($root.$path,0777,true);
        }


        //罗技英文系统 文件编码没搞定 暂时用这种
        $xpath = $path . uuid() . (empty($ext)?"":".".$ext);

        copy($file_path,$root.$xpath);


        $arr = array();
        $arr["file_name"] = $file_name;
        $arr["file_type"] = $file_type;
        $arr["file_size"] = $file_size;
        $arr["file_ext"] = $ext;
        $arr["file_url"] = $xpath;
        $arr["rel"] = $rel;

        Db::name('ps_upload')->insert($arr);

        $arr['size'] = $size;
        $arr['size_limit'] = $size_limit;
        return json(array('code' => 0,'data'=>$arr));
    }

    /**
     * by   hugh
     * use  上传文件
     * time 2020/5/13 16:38
     */
    public function delfile()
    {
        $id = input('id/d',0);

        $row = Db::name('ps_upload')->where(['id'=>$id])->find();

        if(isset($row)){
            $root = ROOT_PATH . "public";

            $path = $root . iconv('utf-8', 'gb2312',$row['file_url']);

            if(file_exists($path)){
                unlink($path);
            }

            Db::name('ps_upload')->where(['id'=>$id])->delete();

            return json(array('code' => 0,'text'=>"删除成功"));

        }
        else {
            return json(array('code' => 1,'text'=>"删除失败！没有此文件"));
        }
    }

}